import { defineStore } from 'pinia'
import { ServeFindUserEmoticon, ServeUploadEmoticon, ServeDeleteEmoticon } from '@/api/emoticon'
import { ServeCollectEmoticon } from '@/api/chat'

const message = window['$message']

export const useEditorStore = defineStore('editor', {
  state: () => {
    return {
      // 表包相关
      emoticon: {
        items: [
          {
            name: '系统表情',
            icon: ''
          },
          {
            name: '我的收藏',
            icon: '',
            children: []
          }
        ]
      }
    }
  },
  actions: {
    // 加载用户表情包
    loadUserEmoticon() {
      ServeFindUserEmoticon().then((res) => {
        if (res.code == 200) {
          const { collect_emoticon } = res.data

          // 用户收藏的系统表情包
          this.emoticon.items[1].children = collect_emoticon || []
        }
      })
    },

    // 收藏用户表情包
    saveUserEmoticon(resoure) {
      ServeCollectEmoticon({
        record_id: resoure.record_id
      }).then((res) => {
        if (res.code == 200) {
          this.loadUserEmoticon()
        } else {
          message.warning(res.message)
        }
      })
    },

    // 自定义上传用户表情包
    uploadUserEmoticon(file) {
      const data = new FormData()
      data.append('emoticon', file)

      ServeUploadEmoticon(data).then((res) => {
        if (res.code == 200) {
          this.emoticon.items[1].children.unshift(res.data)
        } else {
          message.warning(res.message)
        }
      })
    },

    // 自定义上传用户表情包
    removeUserEmoticon(resoure) {
      ServeDeleteEmoticon({
        ids: [resoure.id].join(',')
      }).then((res) => {
        if (res.code == 200) {
          this.emoticon.items[1].children.splice(resoure.index, 1)
          message.success('删除成功')
        } else {
          message.warning(res.message)
        }
      })
    }
  }
})
